package com.hdax.auth.controller;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hdax.auth.feign.MemberFeignService;
import com.hdax.auth.feign.ThirdPartFeignService;
import com.hdax.auth.vo.UserLoginVo;
import com.hdax.auth.vo.UserRegistVo;
import com.hdax.common.constant.AuthConstant;
import com.hdax.common.exception.BizCodeEnume;
import com.hdax.common.to.MemberEntity;
import com.hdax.common.utils.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {

    @Autowired
    private ThirdPartFeignService thirdPartFeignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private ObjectMapper objectMapper;


    /**
     * 远程调用发送短信(60秒只能发送一次验证码)
     * @param phone
     * @param
     * @return
     */
    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone){
        String rediCode = redisTemplate.opsForValue().get(AuthConstant.SMS_CODE_CACHE_PREFIX+phone);
        //缓存中有就判断
        if(!StringUtils.isEmpty(rediCode)){
            Long codeTime = Long.parseLong(rediCode.split("_")[1]);
            if(System.currentTimeMillis() - codeTime < 60000){
                //60秒内禁止再次发送验证码
                return R.error(BizCodeEnume.VALUE_SSM_CODE.getCode(),BizCodeEnume.VALUE_SSM_CODE.getMsg());
            }
        }
        //缓存中没有当前手机号的验证码，或者时间已经超过60秒重新生成随机验证码
        //毫秒为单位的当前时间
        String substring = (int)((Math.random()*9+1)*1000)+"_"+System.currentTimeMillis();
        System.out.println("验证码"+substring);
        //验证码存入缓存，十分钟内有效，缓存的目的就是为了注册时候的校验
        redisTemplate.opsForValue().set(AuthConstant.SMS_CODE_CACHE_PREFIX+phone,substring,10, TimeUnit.MINUTES);
        //调用远程服务发送验证码
        thirdPartFeignService.sendCode(phone,substring.split("_")[0]);
        return R.ok();
    }


    /**
     * 注册
     */
    /**
     * RedirectAttributes redirectAttributes:从定向携带数据
     * @param
     * @param
     * @return
     */
    @PostMapping("/register")
    public String regis(@Valid UserRegistVo vos, BindingResult result, RedirectAttributes attributes){
        //如果校验有问题获取验证的错误消息
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        //获取验证码
        String code = vos.getCode();
        String s = redisTemplate.opsForValue().get(AuthConstant.SMS_CODE_CACHE_PREFIX + vos.getPhone());
        //验证码再缓存中存在
        if(!StringUtils.isEmpty(s)){
            //判断缓存中的验证码，和传过来的验证码是否一致
            if(code.equals(s.split("_")[0])){
                //验证码通过，调用远程服务实现注册功能
                redisTemplate.delete(AuthConstant.SMS_CODE_CACHE_PREFIX + vos.getPhone());
                //调用用户服务进行注册，参数为用户对应的注册信息
                R regist = memberFeignService.regist(vos);
                Integer code1 = (Integer) regist.get("code");
                if(code1==0){
                    return "redirect:http://auth.gulimall.com/login.html";
                }else{
                    Map<String,Object> map=new HashMap<>();
                    map.put("msg",regist.get("code"));
                    attributes.addFlashAttribute("errors",map);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            }else {
                //验证码错误返回注册页面
                Map<String, String> errors = new HashMap<>();
                errors.put("code","验证码错误");
                attributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.gulimall.com/reg.html";

            }
        }else{
            //缓存中没有当前手机号的验证码返回注册页面
            Map<String, String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";

        }
    }


    /**
     * 登录
     */
    @ResponseBody
    @GetMapping("/login")
    public R login(@RequestParam("loginacct")String loginacct, @RequestParam("password")String password, HttpSession session) throws JsonProcessingException {
        UserLoginVo userLoginVo=new UserLoginVo();
        userLoginVo.setLoginacct(loginacct);
        userLoginVo.setPassword(password);
        //远程服务判断用户是否存在账号密码是否正确
        R login = memberFeignService.login(userLoginVo);
        Object data = login.get("data");
        if((Integer) login.get("code")==0){
            MemberEntity memberEntity;
            if (data instanceof String v) {
                memberEntity = objectMapper.readValue(v, MemberEntity.class);
            } else {
                memberEntity = objectMapper.readValue(objectMapper.writeValueAsString(data), MemberEntity.class);
            }
            session.setAttribute("loginUser", memberEntity);
            return R.ok();
        }else{
            return R.error(BizCodeEnume.LOGINACCT_PASSWORD.getCode(),BizCodeEnume.LOGINACCT_PASSWORD.getMsg());
        }
    }
}
